"""Custom fields and widgets."""

from hcp.forms.multi import MultiDynamicWidget, MultiDynamicField
from django.forms.util import flatatt
from hcp.forms.grouped import GroupedForm
from django.utils.safestring import mark_safe

class MyDynamicWidget(MultiDynamicWidget):

    def format_output(self, rendered_widgets, name):
        output = []
        for index, rendered_widget in enumerate(rendered_widgets):
            output.append(u'<div class="row-%s">' % (name,))
            output.append(rendered_widget)
            attrs = {
                'type': 'button',
                'tabindex': '-1',
                'class': 'hcp-button-delete',
                'onclick': mark_safe('delete_field(\'%s\', this)' % (name,)),
            }
            if len(rendered_widgets) == 1:
                attrs['style'] = 'display:none;'
            output.append(u'<input%s />' % flatatt(attrs))

            attrs = {
                'type': 'button',
                'tabindex': '-1',
                'class': 'hcp-button-add',
                'onclick': mark_safe('add_field(\'%s\')' % (name,)),
            }
            if index+1 != len(rendered_widgets):
                attrs['style'] = 'display:none;'
            output.append(u'<input%s />' % flatatt(attrs))
            output.append(u'</div>')

        return u'\n'.join(output)


class MyDynamicField(MultiDynamicField):

    def __init__(self, *args, **kwargs):
        if not 'widget' in kwargs:
            kwargs['widget'] = MyDynamicWidget
        super(MyDynamicField, self).__init__(*args, **kwargs)


class MyGroupedForm(GroupedForm):

    def __init__(self, *args, **kwargs):
        super(MyGroupedForm, self).__init__(group_attrs={'class': 'hcp-table'},
                                            section_header_attrs={'class': 'hcp-table-heading'},
                                            label_attrs={'class': 'hcp-table-label'},
                                            *args, **kwargs)
